<template>
    <div class="ls-add-admin">
        <div class="ls-card">
            <el-page-header @back="$router.go(-1)" :content="identity?'编辑商城':'新增商城'" />
        </div>

        <div class="ls-card m-t-16 p-20">
            <el-form :rules="rules" ref="form" :model="form" label-width="120px" size="small">
                <!-- 商城名称 -->
                <el-form-item label="商城名称" prop="name">
                    <el-input class="ls-input" v-model="form.name" placeholder="请输入账号商城名称">
                    </el-input>
                </el-form-item>
                <!-- 域名别名 -->
                <el-form-item label="域名别名" v-if="identity">
                  <el-input class="ls-input" v-model="form.domain_alias" show-word-limit placeholder="请输入域名别名">
                  </el-input>
                  <template >
                    是否验证域名
                    <el-checkbox v-model="form.is_check_domain" :true-label="1" :false-label="0" label="（商城上线后，请勾选验证域名）"></el-checkbox>
                  </template>
                  <div class="muted">
                    当前域名：{{form.shop_url}}
                  </div>
                </el-form-item>
                <!-- 管理员账号 -->
                <el-form-item label="管理员账号" prop="super_admin" v-if="!identity">
                    <el-input class="ls-input" v-model="form.super_admin" placeholder="请输入管理员账号">
                    </el-input>
                    <div class="muted xs m-l-16">商城管理后台的超级管理员账号</div>
                </el-form-item>
                <!-- 密码输入框 -->
                <el-form-item label="管理员密码" prop="super_password" v-if="!identity">
                    <el-input class="ls-input" v-model="form.super_password" show-word-limit placeholder="请输入管理员密码">
                    </el-input>
                </el-form-item>
                <!-- 确认密码输入框 -->
                <el-form-item label="确认密码" prop="super_password_confirm" v-if="!identity">
                    <el-input class="ls-input" v-model="form.super_password_confirm" show-word-limit
                        placeholder="请输入确认密码">
                    </el-input>
                </el-form-item>
                <!-- 联系人姓名 -->
                <el-form-item label="联系人姓名" prop="contact">
                    <el-input class="ls-input" v-model="form.contact" show-word-limit placeholder="请输入联系人姓名">
                    </el-input>
                </el-form-item>
                <!-- 商城套餐 -->
                <el-form-item label="商城套餐" prop="set_meal_id">
                  <el-select class="ls-input" v-model="form.set_meal_id" placeholder="请选择">
                    <el-option :label="item.name" :value="item.id" v-for="(item) in setMealData" :key="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <!-- 套餐到期时间 -->
                <el-form-item label="套餐到期时间" prop="expires_time">
                  <el-date-picker format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" v-model="form.expires_time"  type="date" placeholder="选择日期">
                  </el-date-picker>
                  <history-meal v-if="identity" :id="identity"></history-meal>
                </el-form-item>
                <!-- 备注 -->
                <el-form-item label="备注">
                  <el-input class="ls-input" type="textarea" :rows="5" placeholder="请输入内容" v-model="form.remark">
                  </el-input>
                </el-form-item>
              <!-- 联系人方式 -->
              <el-form-item label="联系人方式" prop="contact_mobile">
                <el-input class="ls-input" v-model="form.contact_mobile" show-word-limit placeholder="请输入联系人方式">
                </el-input>
              </el-form-item>
                <!-- 商城状态 -->
                <el-form-item label="商城状态" required>
                    <el-radio-group v-model="form.status">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="0">关闭</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
        </div>

      <div class="ls-card ls-top__data m-t-16" v-if="identity">
        <div class="f-w-500 sm m-b-10">
          商城数据
        </div>
        <div class="content">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="m-b-8 xxl">{{form.shop_data.total_order_amount}}
              </div>
              <div class="lighter xs">营业额</div>
            </el-col>
            <el-col :span="6">
              <div class="m-b-8 xxl">{{form.shop_data.order_num}}</div>
              <div class="lighter xs">成交单数</div>
            </el-col>
            <el-col :span="6">
              <div class="m-b-8 xxl">{{form.shop_data.goods_count}}
              </div>
              <div class="lighter xs">商品数量/件</div>
            </el-col>
            <el-col :span="6">
              <div class="m-b-8 xxl">{{form.shop_data.user_count}}</div>
              <div class="lighter xs">用户人数</div>
            </el-col>
          </el-row>
        </div>
      </div>

        <!-- 底部保存或取消 -->
        <div class="bg-white ls-fixed-footer">
            <div class="row-center flex" style="height: 100%;">
                <el-button size="small" @click="$router.go(-1)">取消</el-button>
                <el-button size="small" type="primary" @click="onSubmit('form')">保存</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator'
import { apiShopDetail, apiShopAdd, apiShopEdit, apiSetMealLists } from '@/api/shop'
import historyMeal from './components/history-meal.vue'
import { debounce } from '@/utils/util'
import lsPagination from '@/components/ls-pagination.vue'
import ExportData from '@/components/export-data/index.vue'
import LsDialog from '@/components/ls-dialog.vue'

@Component({
  components: {
    historyMeal
  }
})
export default class ListsDetail extends Vue {
  /** S Data **/

    identity: number | null = null; // 当前编辑用户的身份ID

    setMealData: any = []

    // 添加商城表单数据
    form: any = {
      name: '', // 名称
      super_admin: '', // 账号
      super_password: '', // 密码
      super_password_confirm: '', // 确认密码
      status: 1, // 商城状态 0-停止服务 1-开启服务
      contact: '', // 联系人
      contact_mobile: '', // 联系人手机号
      domain_alias: '', // 域名别名
      is_check_domain: 1, // 是否验证域名
      shop_url: '', // 当前域名
      set_meal_id: '', // 套餐ID
      expires_time: '', // 到期时间
      remark: '', // 备注
      shop_data: {}
    };

    // 表单校验
    rules = {
      name: [{ required: true, message: '请输入商城名称', trigger: 'blur' }],
      super_admin: [
        { required: true, message: '请输入商城名称', trigger: 'blur' }
      ],
      super_password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        {
          validator: (rule: object, value: string, callback: any) => {
            !value ? callback(new Error('请输入密码')) : callback()
          },
          trigger: 'blur'
        }
      ],
      super_password_confirm: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
          validator: (rule: object, value: string, callback: any) => {
            if (this.form.password) {
              if (!value) callback(new Error('请再次输入密码'))
              if (value !== this.form.password) { callback(new Error('两次输入密码不一致!')) }
            }
            callback()
          },
          trigger: 'blur'
        }
      ],
      set_meal_id: [{ required: true, message: '请选择套餐', trigger: ['blur', 'change'] }],
      expires_time: [{ required: true, message: '请选择到期时间', trigger: ['blur', 'change'] }]
    };

    /** E Data **/

    /** S Methods **/
    // 点击表单提交
    onSubmit (formName: string) {
      // 验证表单格式是否正确
      const refs = this.$refs[formName] as HTMLFormElement
      refs.validate((valid: boolean): any => {
        if (!valid) return

        if (!this.identity) {
          this.handleShopAdd()
        } else {
          this.handleShopEdit()
        }
      })
    }

    // 添加商城
    async handleShopAdd (): Promise<void> {
      await apiShopAdd({ ...this.form })
      setTimeout(() => this.$router.go(-1), 500)
    }

    // 编辑商城
    async handleShopEdit (): Promise<void> {
      await apiShopEdit({ ...this.form, id: this.identity })
      setTimeout(() => this.$router.go(-1), 500)
    }

    // 获取详情
    async getShopDetailFunc (): Promise<void> {
      const res: any = await apiShopDetail({
        id: this.identity as number
      })
      Object.keys(res).map((key) => {
        this.$set(this.form, key, res[key])
      })
    }

    // 获取套餐列表
    async getSetMealLists (): Promise<void> {
      const { lists } = await apiSetMealLists({status: 1})
      this.setMealData = lists
    }
    /** E Methods **/

    /** S Life Cycle **/
    created () {
      const query: any = this.$route.query

      // 编辑模式：初始化数据
      this.identity = +query.id
      if (+query.id) {
        this.getShopDetailFunc()
      }

      this.onSubmit = debounce(this.onSubmit, 2000)
      this.getSetMealLists()
    }
    /** E Life Cycle **/
}
</script>

<style lang="scss" scoped>
.ls-add-admin {
    padding-bottom: 80px;

    .ls-input {
        width: 380px;
    }
}
</style>
